﻿(function () {
    "use strict";

    var appViewState = Windows.UI.ViewManagement.ApplicationViewState;
    var binding = WinJS.Binding;
    var nav = WinJS.Navigation;
    var ui = WinJS.UI;
    var utils = WinJS.Utilities;

    var bShowFullScreen = false;
    var imgHeight = 0;
    var curRowWidths = [];
    var curImgIdx = 0;
    var curPageURL = null;
    var imgItems = null;

    var waitedTimeForImgWall = 0;

    var barTimeEvt = null;

    ui.Pages.define("/pages/split/split.html", {

        /// <field type="WinJS.Binding.List" />
        _items: null,
        _group: null,
        
        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {
            var listView = element.querySelector(".imgWall");
            curPageURL = (options && options.pageURL !== null) ? options.pageURL : null;
            if (curPageURL === null) {
                nav.back(1);
                return;
            }
            
            document.querySelector("header[role=banner] .pagetitle").textContent = Data.getGroupTitle(curPageURL);
            curImgIdx = 0;
            imgHeight = Math.floor((document.body.offsetHeight - 150 - 20) / 3);
            curRowWidths = [0, 0, 0];

            var group = (curPageURL !== null) ? Data.resolveGroupReference(curPageURL, initialImgWall) : null;
            
            $(".imgWall").scroll(function () {
                console.log($(".imgWall").scrollLeft());
                console.log(curRowWidths.max() - $(window).width());
                if ($(".imgWall").scrollLeft() > curRowWidths.max() - $(window).width() - 20) {
                    loadImg(imgItems, 20);
                }
            });
                        
            if (nav.canGoBack && nav.history.backStack[nav.history.backStack.length - 1].location === "/pages/split/split.html") {
                // Clean up the backstack to handle a user snapping, navigating
                // away, unsnapping, and then returning to this page.
                nav.history.backStack.pop();                
            }
        },

        unload: function () {
            if (imgItems) {
                imgItems.dispose();

                // Clear list to enforce re-cache thumbnail for local resources, which was created for one-time use only                
                if (curPageURL !== "" && curPageURL.indexOf("http://") === -1) {
                    Data.list.splice(0, Data.list.length);
                }
            }
        }
    });

    function initialFlipView(imgItems) {
        var imgFlipViewHolder = document.querySelector(".full-flip");
        imgFlipViewHolder.style.visibility = "hidden";
        var imgFlipView = imgFlipViewHolder.winControl;
        imgFlipView.itemDataSource = imgItems.dataSource;
        imgFlipView.itemTemplate = document.querySelector(".imgtemplate");
        imgFlipView.currentPage = 0;
        imgFlipView.onpagecompleted = function () {
            var imgHolders = document.querySelectorAll(".img-section");
            for (var idx = 0; idx < imgHolders.length; ++idx) {
                imgHolders[idx].style.width = document.documentElement.offsetWidth + "px";
                imgHolders[idx].style.height = document.documentElement.offsetHeight + "px";
            }

            var imgs = document.querySelectorAll(".img-source");
            for (var idx = 0; idx < imgs.length; ++idx) {
                if (imgs[idx].width == 0 || imgs[idx].height == 0) {
                    imgs[idx].style.width = "auto";
                    imgs[idx].style.height = "auto";
                }
                else if (imgs[idx].height * document.documentElement.offsetWidth / imgs[idx].width > document.documentElement.offsetHeight) {
                    imgs[idx].style.height = document.documentElement.offsetHeight + "px";
                    imgs[idx].style.width = "auto";                    
                }
                else {
                    imgs[idx].style.width = document.documentElement.offsetWidth + "px";
                    imgs[idx].style.height = "auto";
                }
            };
        }

        $(".img-overlay .win-backbutton").css("margin-top", "0px");
        $(".img-overlay .win-backbutton").css("margin-left", "10px");
        $(".img-overlay").hide();

        $(".full-image").click(function () {
            if (barTimeEvt) {
                clearTimeout(barTimeEvt);
            }
            $(".img-overlay").slideDown(200);
            barTimeEvt = setTimeout(function () {
                $(".img-overlay").slideUp(200);
                $(".img-overlay").hide();
            }, 3000);
        });
    }

    function initialImgWall() {
        if (waitedTimeForImgWall > 2000) {
            waitedTimeForImgWall = 0;
            nav.back(1);
            return;
        }

        waitedTimeForImgWall += 500;
        imgItems = Data.getItemsFromGroup(curPageURL);
        if (imgItems.length == 0) {
            // Wait for the image to load
            setTimeout(initialImgWall, 500);
            return;
        }
        else {
            //setTimeout(function () {
            initialFlipView(imgItems);
            loadImg(imgItems, 40);
            waitedTimeForImgWall = 0;
            //}, 100);
        }
    }

    function postLoadMoreImgForGroup() {
        imgItems = Data.getItemsFromGroup(curPageURL);
        if (curImgIdx < imgItems.length) {
            loadImg(imgItems, 40);
        }
    }
   
    function loadImg(items, loadQuote) {        
        var listView = $(".imgWall");
        
        if (Data.getMoreImgForGroup && curImgIdx >= items.length) {
            Data.getMoreImgForGroup(curPageURL, postLoadMoreImgForGroup);
            return;
        }

        for (var loaded = 0; curImgIdx < items.length && loaded < loadQuote; ++curImgIdx, ++loaded) {
            var curOrignHeight = items.getItem(curImgIdx).data.height;
            var curOrignWidth = items.getItem(curImgIdx).data.width;

            if (curOrignHeight && curOrignWidth && curOrignHeight != "0" && curOrignWidth != "0") {
                var curScaledWidth = Math.floor(imgHeight * curOrignWidth / curOrignHeight) + 5;
                var minIdx = curRowWidths.minIdx();

                var newDivItem = document.createElement("div");
                newDivItem.setAttribute("class", "item");
                newDivItem.setAttribute("page", curImgIdx);
                newDivItem.style.paddingLeft = curRowWidths[minIdx] + "px";
                newDivItem.style.paddingTop = (imgHeight + 5) * minIdx + "px";
                newDivItem.style.position = "absolute";
                newDivItem.style.display = "inline";
                newDivItem.style.height = imgHeight + "px";

                newDivItem.onclick = function () {                    
                    document.querySelector(".splitpage").style.visibility = "hidden";
                    document.querySelector(".full-flip").style.visibility = "visible";
                    document.querySelector(".full-flip").winControl.currentPage = this.getAttribute("page");
                    //nav.navigate("/pages/fullscreen/fullscreen.html", { curPage: this.getAttribute("page"), pageURL: curPageURL });
                };

                // Append img
                var newImgItem = document.createElement("img");
                newImgItem.setAttribute("src", items.getItem(curImgIdx).data.backgroundImage);
                newImgItem.setAttribute("title", items.getItem(curImgIdx).data.caption);
                newImgItem.setAttribute("class", "item-image");
                newImgItem.style.height = imgHeight + "px";
                newImgItem.style.width = "auto";
                newDivItem.appendChild(newImgItem);

                listView.append(newDivItem);
                curRowWidths[minIdx] += curScaledWidth;
                $(".progress").hide();                
            }
            else {
                var newImg = new Image();
                newImg.name = items.getItem(curImgIdx).data.caption;
                newImg.src = items.getItem(curImgIdx).data.backgroundImage;
                newImg.alt = curImgIdx;
                newImg.onload = function () {
                    var curOrignHeight = this.height;
                    var curOrignWidth = this.width;
                    PhotoDB.updateImgSize(this.src, curOrignWidth, curOrignHeight)

                    var curScaledWidth = Math.floor(imgHeight * curOrignWidth / curOrignHeight) + 5;
                    var minIdx = curRowWidths.minIdx();

                    var newDivItem = document.createElement("div");
                    newDivItem.setAttribute("class", "item");
                    newDivItem.setAttribute("page", this.alt);
                    newDivItem.style.paddingLeft = curRowWidths[minIdx] + "px";
                    newDivItem.style.paddingTop = (imgHeight + 5) * minIdx + "px";
                    newDivItem.style.position = "absolute";
                    newDivItem.style.display = "inline";
                    newDivItem.style.height = imgHeight + "px";
                    //newDivItem.style.display = "-ms-grid";
                    //newDivItem.style.msGridRowss = "1fr 90px";

                    newDivItem.onclick = function () {
                        document.querySelector(".splitpage").style.visibility = "hidden";
                        document.querySelector(".full-flip").style.visibility = "visible";
                        document.querySelector(".full-flip").winControl.currentPage = this.getAttribute("page");
                        //nav.navigate("/pages/fullscreen/fullscreen.html", { curPage: this.getAttribute("page"), pageURL: curPageURL });
                    };

                    // Append img
                    var newImgItem = document.createElement("img");
                    newImgItem.setAttribute("src", this.src);
                    newImgItem.setAttribute("title", this.name);
                    newImgItem.setAttribute("class", "item-image");
                    newImgItem.style.height = imgHeight + "px";
                    newImgItem.style.width = "auto";
                    newDivItem.appendChild(newImgItem);

                    // Append overlay
                    //var newOverLayItem = document.createElement("div");                
                    //newOverLayItem.setAttribute("class", "item-overlay");
                    //var newDescription = document.createElement("h2");
                    //newDescription.setAttribute("class", "item-description");
                    //newDescription.innerText = this.name;
                    //newOverLayItem.appendChild(newDescription);
                    //newDivItem.appendChild(newOverLayItem);

                    //var strHTML = "<div class=\"item\" style=\"height: " + imgHeight + "px; padding-top: " + (imgHeight + 5) * minIdx + "px; padding-left: " + curRowWidths[minIdx] + "px;\" page=\"" + this.alt + "\"><img width=\"" + curOrignWidth + "px\" height=\"" + curOrignHeight + "px\" title=\"" + this.name + "\" class=\"item-image\" style=\"height: " + imgHeight + "px;\" src=\"" + this.src + "\"></div>";
                    //listView.innerHTML += toStaticHTML(strHTML);

                    listView.append(newDivItem);
                    curRowWidths[minIdx] += curScaledWidth;
                    $(".progress").hide();
                }
            }
        }
    }
})();